<script setup lang="ts">
import { computed, isVNode, Ref } from 'vue';

import { ProTablePlus } from '@package/table';
import useTable from '@/hooks/useTable';
import { TProTable } from './ProTable.vue';

type TProTableUtal = { 
  formCol?: any;
  formItems?: any[];

  fetchUrl: string | Ref<string>;
  fetchOptions?: any;
} & Omit<TProTable, 'list' | 'loading'>;

// props
const {
  concise = false,
  fetchUrl,
  fetchOptions,
  columns,
  formCol,
  ...props
} = defineProps<TProTableUtal>();

const emits = defineEmits<{
  change: [event: any[]];
}>();

// 获取数据列表
const {
  list,
  isFetching,
  search,
  pagination,
  submit,
  reset,
  refresh,
  execute,
  bindNodeForPlus,
  onFetchResponse,
} = useTable(fetchUrl, fetchOptions);

onFetchResponse(() => {
  emits('change', list.value);
});

const slots = defineSlots<{
  default(): any;
}>();

const slotMap = computed(() => {
  const list = slots.default?.() || [];
  return list.reduce((obj: any, item: any) => {
    const name = item.type.name;
    if (isVNode(item) && ['ProTableScope', 'ProFormScope'].includes(name)) {
      Reflect.set(obj, name, item);
    }
    return obj;
  }, {});
});

defineExpose({
  list,
  refresh,
  jump: (page: number = 1) => {
    pagination.page = page;
    execute();
  },
});

</script>

<template>
  <ProTablePlus
    v-bind="props"
    :concise="concise"
    :ref="bindNodeForPlus"
    :col="formCol"
    :list="list"
    :search="search"
    :loading="isFetching"
    :pagination="pagination"
    :columns="columns"
    :form-items="formItems"
    @submit="submit"
    @reset="reset"
  >
    <component :is="slotMap?.ProTableScope" />

    <template #form>
      <component :is="slotMap?.ProFormScope" />
    </template>

    <!-- <template #tableFooter>
      <slot name="tableFooter" />
    </template> -->
  </ProTablePlus>
</template>
